package cn.sylinx.horm.proxy.mapper.invoker;

import java.util.Map;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.proxy.mapper.MapperMethodMetadata;
import cn.sylinx.horm.proxy.mapper.parse.SqlItem;
import cn.sylinx.horm.util.Tuple;

class BeanPageMapperInvoker extends AbstractMapperInvoker {

    @Override
    public Object invoke(MapperMethodMetadata methodMetadata, Tuple tuple) {

        Map<String, Object> params = tuple.getObject(0);
        int pageNumber = tuple.getObject(1);
        int pageSize = tuple.getObject(2);

        Class<?> truelyReturnType = methodMetadata.getTruelyReturnType();

        Tuple mapper = getMapper(methodMetadata);

        SqlItem sqlItem = mapper.getObject(1);
        String nativeSql = sqlItem.getStatement();

        String truelyDatasource = mapper.getObject(2);
        SqlClient ormClient = getClient(truelyDatasource);
        String parseSqlType = getParseSqlType(sqlItem.getParseSqlType());
        
        // 使用native sql
        Tuple t = ormClient.parseSql(nativeSql, parseSqlType, params);
        String truelyNativeSql = t.getObject(0);
        Object[] truelyParams = t.getObject(1);

        return ormClient.queryPage(truelyNativeSql, pageNumber, pageSize, truelyParams, truelyReturnType);
    }
}
